const { createServer, request } = require('http')
function req(opt) {
  return new Promise((resolve, reject) => {
    let options = {
      host: '101.52.127.20',
      port: '8002',
      method: opt.method || 'GET',
      path: opt.path || '/gateway',
      body: opt.data,
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(opt.data),
        ...opt.headers
      }
    }
    let req = request(options, (res) => {
      let data = ''
      res.on('data', (chunk) => {
        data += chunk
      })
      res.on('end', () => {
        resolve(JSON.parse(data))
      })
      res.on('error', (err) => {
        reject(err)
      })
    })
    req.write(opt.data)
    req.on('error', (err) => {
      reject(err)
    })
    req.end()
  })
}

function getPhone(phone) {
  return req({
    method: 'POST',
    path: '/gateway/xj-user/v1/getCode',
    data: JSON.stringify({
      token: 'cqlmAdmin123',
      phone: phone
    })
  })
}

const app = {
  executeStack: [],
  use(fn) {
    this.executeStack.push(fn)
  }
}

app.use(async (ctx) => {
  const { req, res } = ctx
  let reg = new RegExp('/phone/(.*?)')
  if (reg.test(req.url)) {
    const phone = req.url.replace(reg, '$1')
    await getPhone(phone).then(data => {
      console.log(`${phone} --> ${data.result}`)
      ctx.body = data.result || '请重新发送！'
    }, err => {
      console.log(err)
      res.statusCode = 500
    })
  }
})

const serve = createServer((req, res) => {
  let ctx = {
    req, res
  }
  let index = -1
  function dispatch(i) {
    if (index >= i) {
      return Promise.resolve()
    }
    if (i == app.executeStack.length) {
      return Promise.resolve()
    }
    index = i
    let fn = app.executeStack[i]

    if (!fn) {
      return Promise.resolve()
    }
    try {
      return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1)))
    } catch (error) {
      return Promise.reject(error)
    }
  }
  return dispatch(0).then(() => {
    let data = ctx.body
    if (ctx.body) {
      res.writeHead(200, { 'Content-Type': 'application/json;charset=utf8', 'Content-Length': Buffer.byteLength(data) })
    }
    res.end(data)
  }, err => {
    res.statusCode = 500
    console.log(err)
    res.end('系统错误')
  })
})


const port = 9090

serve.listen(port, () => {
  console.log(`服务启动成功!\nhttp://localhost:${port}/phone/`)
})
